package com.sunlake.spring.main.model.orders.task;

import com.sunlake.spring.main.model.account.mapper.RechargeBillsMapper;
import com.sunlake.spring.main.model.account.po.RechargeBills;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author liuha
 */
@Component
@Slf4j
public class OrderStatusCheckTask {

    @Autowired
    private RechargeBillsMapper rechargeBillsMapper;

    /**
     * 每分钟检查一次过期订单
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void checkExpiredOrders() {
        try {
            List<RechargeBills> pendingOrders = rechargeBillsMapper.selectExpiredPendingOrders();
            LocalDateTime now = LocalDateTime.now();
            String nowStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            for (RechargeBills order : pendingOrders) {
                log.info("发现过期订单，更新状态为失败：订单号={}", order.getRechargeNo());
                rechargeBillsMapper.updateStatusByRechargeNo(
                        order.getRechargeNo(), "FAILED", null, nowStr, nowStr);
            }
        } catch (Exception e) {
            log.error("检查过期订单异常：", e);
        }
    }
}
